<script setup>
import { ref } from 'vue'
import { login } from '@/api/api'
import { ElMessage } from 'element-plus'
import router from '@/router/index'

const loginform = ref({
  username: '',
  password: ''
})
const loginRules = ref({
  username: [
    { required: true, message: '账号不能为空！', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度在3-20位之间！', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空！', trigger: 'blur' },
    { min: 3, max: 60, message: '密码长度在3-60位之间！', trigger: 'blur' },
  ]
})
const loginFormRef = ref(null)

const onSubmit = async () => {
  if (!loginFormRef.value) return
  await loginFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      let result = await login(loginform.value)
      if (result.code) {
        localStorage.setItem('loginUser', JSON.stringify(result.data))
        
        // 跳转至主页,路由
        ElMessage.success('登录成功！')
        router.push('/usermanage')
      } else {
        ElMessage.error('登录失败！')
      }
    } else {
      console.log('校验失败！', fields)
    }
  })
}
</script>

<template>
  <div class="login">
    <el-form ref="loginFormRef" :model="loginform" :rules="loginRules" label-width="auto" class="login-form">
    <h3 class="title">WNS</h3>
    <el-form-item label="用户名">
      <el-input v-model="loginform.username" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="loginform.password" type="password"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" class="login-btn">登入</el-button>
      <el-button type="primary" @click="register" class="login-btn">注册</el-button>
    </el-form-item>
     <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
      </div>
</el-form>
  </div>

</template>

<style scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  width: 100vw;
  background-image: url("@/assets/images/login.png");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  position: fixed;
  top: 0;
  left: 0;
}

.title {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.login-form {
  background-color: rgba(255, 255, 255, 0.8);
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  max-width: 400px;
  width: 100%;
}

.login-btn {
  width: 45%;
}
</style>